from datetime import timedelta,datetime

from odoo import models, fields, api
from odoo.exceptions import UserError


class HREmployee(models.Model):
    _inherit = 'hr.employee'
    resource_calendar_id_1 = fields.Many2one('resource.calendar', compute='compute_resource_calendar_id')
    calendar_period_ids = fields.One2many('employee.calendar.period', 'employee_id')

    pin=fields.Char(compute='compute_pin',store=True)
    @api.depends('barcode')
    def compute_pin(self):
        for employee in self:
            if employee.barcode:
                if employee.barcode.startswith('9'):
                    employee.pin=employee.barcode
                else:
                    employee.pin=str(int("".join(filter(str.isdigit, employee.barcode))))
            else:
                employee.barcode=''

    def update_employee_bin(self):
        pass
        # records=self.env['hr.record'].search([])
        # for record in records:
        #     record.compute_show_card_date_time()

        # employee_ids=self.env['hr.employee'].search([])
        # for employee in employee_ids:
        #     employee.compute_pin()
    def get_month_over_time(self,month_time):
        report_ids = self.env['hr.attendance.report'].search(
            [('employee_id', '=', self.id), ('month_time', '=', month_time)])
        if report_ids:
            return sum(float(report.is_late) for report in report_ids)
        else:
            return 0

    def get_month_late_time(self, month_time):
        report_ids=self.env['hr.attendance.report'].search([('employee_id','=',self.id),('month_time','=',month_time)])
        if report_ids:
            return sum(float(report.is_late) for report in report_ids)
        else:
            return 0


    def get_month_absent_day(self, month_time):
        report_ids = self.env['hr.attendance.report'].search(
            [('employee_id', '=', self.id), ('month_time', '=', month_time),('is_absent','=',True)])
        return len(report_ids)

    def get_month_leave_early_time(self, month_time):
        report_ids = self.env['hr.attendance.report'].search(
            [('employee_id', '=', self.id), ('month_time', '=', month_time)])
        if report_ids:
            return sum(float(report.is_leave_early) for report in report_ids)
        else:
            return 0

    def get_month_leave_time(self, month_time):
        pass

    def get_current_calendar_id(self,date):
        line=self.env['employee.calendar.period'].search([('employee_id','=',self.id),('date_start','<=',date),('date_end','>=',date)])
        if len(line)>1:
            raise UserError('%s %s 找到了重复的数据' % (self.name,date))
        if line:
            return line.calendar_id
        elif self.env['resource.calendar'].search([('is_default','=',True)]):
            calendar_id=self.env['resource.calendar'].search([('is_default','=',True)],limit=1)
            return calendar_id
        else:
            return False

    def get_current_calendar_day(self,date):
        calendar_id=self.get_current_calendar_id(date)
        if not calendar_id:
            raise UserError('找不到'+self.name+str(self.date)+'对应的班别')

    def get_employee_monthly_attendance(self,date_start,date_end):
        date1=date_start
        date2=date_end
        need_days=0
        attendance_1=0
        attendance_2=0
        while date1<=date2:
            calendar_id=self.get_current_calendar_id(date1)
            if calendar_id:
                day_of_week=date1.weekday()
                times=calendar_id.attendance_ids.filtered(lambda x:x.dayofweek==str(day_of_week))
                if times:
                    need_days+=1
                    attendance=self.env['hr.attendance'].search([('date','=',date1),('employee_id','=',self.id)])
                    if attendance:
                        if day_of_week in (0,1,2,3,4):
                            attendance_1+=1
                        else:
                            attendance_2+=1
            date1=date1+timedelta(days=1)
        return need_days,attendance_1,attendance_2




    def get_current_calendar_time(self,date):
        print (date)
        day_of_week=date.weekday()
        print (day_of_week)
        settings_1=self.env['hr.holidays.setting'].search(
            [('sheet_type', '=', '1'), ('date', '=', date)])
        settings_2 = self.env['hr.holidays.setting'].search(
            [('sheet_type', '=', '2'), ('date', '=', date)])
        line = self.env['employee.calendar.period'].search(
            [('employee_id', '=', self.id), ('date_start', '<=', date.strftime('%Y-%m-%d')), ('date_end', '>=',date.strftime('%Y-%m-%d'))])
        if line:
            calendar_id=line.calendar_id
        else:
            calendar_id=self.env['resource.calendar'].search([('is_default','=',True)],limit=1)
        if calendar_id:
            times=calendar_id.attendance_ids.filtered(lambda x:x.dayofweek==str(day_of_week))
            if settings_1:
                times = calendar_id.attendance_ids.filtered(lambda x: x.dayofweek == '0')
            if settings_2:
                times=False
            if times:
                if calendar_id.calendar_type=='3':
                    return times[1].hour_from,times[0].hour_to
                else:
                    return times[0].hour_from, times[1].hour_to
        else:
            return False



    def compute_resource_calendar_id(self):
        for r in self:
            if r.calendar_period_ids:
                r.resource_calendar_id_1 = r.calendar_period_ids[0].calendar_id.id
            else:
                r.resource_calendar_id_1 = False


    def get_buka_data(self,start_date,end_date):
        count=self.env['hr.attendance.modify.record'].search_count([
            ('date','>=',start_date),('date','<=',end_date)
        ])
        return  count



class HREmployeePublic(models.Model):
    _inherit = 'hr.employee.public'

    category_ids = fields.Many2many(
        'hr.employee.category', 'employee_category_rel',
        'emp_id', 'category_id', groups="hr.group_hr_manager",
        string='Tags')


    calendar_period_ids = fields.One2many('employee.calendar.period', 'employee_id')

    def compute_resource_calendar_id(self):
        for r in self:
            if r.calendar_period_ids:
                r.resource_calendar_id_1 = r.calendar_period_ids[0].calendar_id.id
            else:
                r.resource_calendar_id_1 = False


